package com.osdp.gateway.util;

import com.osdp.gateway.entity.LoggerEntity;

import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;

/**
 * 网络访问日志
 */
public class LogUtil {
    public static final LoggerEntity logFormat(Long startTime, Long endTime, ServerWebExchange exchange){
        LoggerEntity logger = (LoggerEntity)exchange.getAttributes().get("FILTER_HAS_LOG");
        if(logger == null){
            logger = new LoggerEntity();
            ServerHttpRequest request =  exchange.getRequest();
            String realIP = request.getHeaders().getFirst("X-real-ip");//X-real-ip用来记录服务器的真实地址
            String hostname = StringUtils.isEmpty(realIP) ? request.getRemoteAddress().getHostName() : realIP;
            logger.setUrl(request.getURI().getPath().toString());
            logger.setRemoteAddress(hostname);
            logger.setMethod(request.getMethod().toString());
            logger.setStatusCode(null == exchange.getResponse().getStatusCode() ? 200 : exchange.getResponse().getStatusCode().value());
            logger.setStartTime(startTime);
            logger.setEndTime(endTime);
            logger.setHeader(request.getHeaders().toString());
            logger.setUserAgent(request.getHeaders().getFirst("User-Agent"));
            Route route = (Route)exchange.getAttributes().get(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
            if(route == null){
                logger.setUri(request.getPath().pathWithinApplication().value());
                logger.setUriId("gateway");
            }else{
                logger.setUri(route.getUri().toString());
                logger.setUriId(route.getId());
            }
            exchange.getAttributes().put("FILTER_HAS_LOG", logger);
        }
        return logger;
    }
}
